package com.liuyutao.controller;


import com.liuyutao.pojo.Student;
import com.liuyutao.service.StudentService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/student")
public class StudentController {
    @Autowired
    @Qualifier("studentServiceImpl")
    private StudentService studentService;

    @RequestMapping("/allStudent")
    public String list(Model model, HttpSession session) {
        List<Student> list = studentService.findAllStudent();
        String studentName = session.getAttribute("userLoginInfo").toString();
        model.addAttribute("list", list);
        model.addAttribute("studentName",studentName);
        return "allStudent";
    }

    @RequestMapping("/toAddStudent")
    public String toAddStudent() {
        return "addStudent";
    }

    @RequestMapping("/addStudent")
    public String addStudent(Student student) {
        System.out.println(student);
        studentService.addStudent(student);
        return "redirect:/student/allStudent";
    }

    @RequestMapping("/toUpdateStudent")
    public String toUpdateStudent(Model model, int id) {
        Student student = studentService.findStudentById(id);
        System.out.println(student);
        model.addAttribute("student",student );
        return "updateStudent";
    }

    @RequestMapping("/updateStudent")
    public String updateStudent(Model model, Student student) {
        System.out.println(student);
        studentService.updateStudent(student);
        student = studentService.findStudentById(student.getId());
        model.addAttribute("student", student);
        return "redirect:/student/allStudent";
    }

    @RequestMapping("/del/{id}")
    public String deleteStudent(@PathVariable("id") int id) {
        studentService.deleteStudentById(id);
        return "redirect:/student/allStudent";
    }
    @RequestMapping("queryStudent")
    public String queryStudent(String queryStudentName,Model model){
        Student student = studentService.findStudentByName(queryStudentName);
        List<Student> list = new ArrayList<>();
        list.add(student);
        if (student==null){
            studentService.findAllStudent();
            model.addAttribute("error","未查到");
        }
        model.addAttribute("list" ,list);
        return "allStudent";
    }
}